package com.itheima.controller;

import com.itheima.domian.Permission;
import com.itheima.domian.Role;
import com.itheima.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {


    @Autowired
    private IRoleService iRoleService;
//给角色添加权限
    @RequestMapping("/addPermissionToRole.do")
    public String addRoleToRole(@RequestParam(name = "roleId", required = true) String roleId,
                                @RequestParam(name = "ids", required = true) String[] permissionIds) throws Exception {
//        System.out.println(roleId);
//        System.out.println(permissionIds);
//        System.out.println(1111);
        iRoleService.addRoleToPermission(roleId,permissionIds);
        return "redirect:findAll.do";
    }

//根据roleID查询role，并查询出课添加的权限
    @RequestMapping("/findRoleByIdAndAllpermission.do")
    public ModelAndView findRoleByIdAndAllpermission(@RequestParam(name = "id", required = true)String roleId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Role rolelist = iRoleService.findById(roleId);
        List<Permission> permissions = iRoleService.findOtherPermissions(roleId);
        mv.addObject("role", rolelist);
        mv.addObject("permissionList", permissions);
        mv.setViewName("role-permission-add");
        return mv;
    }


    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Role> roles = iRoleService.findAll();
        mv.addObject("roleList", roles);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("/save.do")
    public String save(Role role) throws Exception {
//        System.out.println(role.toString());
        iRoleService.save(role);
        return "redirect:findAll.do";
    }
}
